package com.codeape.fast.ui.login;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.codeape.fast.R;
import com.codeape.fast.databinding.ActivityLoginBinding;

import timber.log.Timber;

/**
 * 关注 代码猿力，每天学习一点开发新技能，提高开发效率。
 * app/src/main/java/com/codeape/fast/data/model/LoggedInUser.java
 */

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";
    private String login_tips = "关注 代码猿力，每天学习一点开发新技能，提高开发效率";
    private static final String TIPS = "关注 代码猿力，每天学习一点开发新技能，提高开发效率";
    private LoginViewModel mLoginViewModel;

    /**
     * 用户输入的 login name。 LoggedInUser mLoginViewModel
     */
    private String mLogin = "Login user name";
    private ViewGroup mContainer;
    private EditText mUsernameText;
    private EditText mPasswordText;
    private Button mLoginButton;
    private CheckBox mAgreeCheckBox;
    private TextView mAgreeLabel;
    private TextView mAgreeText;
    private ProgressBar mLoading;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mContainer = findViewById(R.id.container);
        mUsernameText = findViewById(R.id.username_text);
        mPasswordText = findViewById(R.id.password_text);
        mLoginButton = findViewById(R.id.login_button);
        mAgreeCheckBox = findViewById(R.id.agree_check_box);
        mAgreeLabel = findViewById(R.id.agree_label);
        mAgreeText = findViewById(R.id.agree_text);
        mLoading = findViewById(R.id.loading);


        mLoginViewModel = new ViewModelProvider(this, new LoginViewModelFactory()).get(LoginViewModel.class);
        mLoginViewModel.getLoginFormState().observe(this, new Observer<LoginFormState>() {
            @Override
            public void onChanged(@Nullable LoginFormState loginFormState) {
                if (loginFormState == null) {
                    Toast.makeText(LoginActivity.this, "test", Toast.LENGTH_SHORT).show();
                    return;
                }

                mLogin = mUsernameText.getText().toString();
                mLoginButton.setEnabled(loginFormState.isDataValid());
                if (loginFormState.getUsernameError() != null) {
                    mUsernameText.setError(getString(loginFormState.getUsernameError()));
                }
                if (loginFormState.getPasswordError() != null) {
                    mPasswordText.setError(getString(loginFormState.getPasswordError()));
                }
            }
        });

        mLoginViewModel.getLoginResult().observe(this, new Observer<LoginResult>() {
            @Override
            public void onChanged(@Nullable LoginResult loginResult) {
                if (loginResult == null) {
                    Timber.w("onChanged: loginResult is null");
                    return;
                }
                mLoading.setVisibility(View.GONE);
                if (loginResult.getError() != null) {
                    showLoginFailed(loginResult.getError());
                }
                if (loginResult.getSuccess() != null) {
                    updateUiWithUser(loginResult.getSuccess());
                }
            }
        });

        TextWatcher afterTextChangedListener = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // ignore
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // ignore
            }

            @Override
            public void afterTextChanged(Editable s) {
                mLoginViewModel.loginDataChanged(mUsernameText.getText().toString(), mPasswordText.getText().toString());
            }
        };
        mUsernameText.addTextChangedListener(afterTextChangedListener);
        mPasswordText.addTextChangedListener(afterTextChangedListener);
        mPasswordText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    Timber.i("onEditorAction: DONE test 2");
                    mLoginViewModel.login(mUsernameText.getText().toString(), mPasswordText.getText().toString());
                }
                return false;
            }
        });

        mLoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean checked = mAgreeCheckBox.isChecked();
                if (checked) {
                    mLoading.setVisibility(View.VISIBLE);
                    mLoginViewModel.login(mUsernameText.getText().toString(), mPasswordText.getText().toString());
                } else {
                    Toast.makeText(LoginActivity.this, "请同意用户协议！", Toast.LENGTH_SHORT).show();
                }
            }
        });

        mAgreeText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });

    }

    private void updateUiWithUser(LoggedInUserView model) {
        String welcome = getString(R.string.welcome) + model.getDisplayName();
        Toast.makeText(getApplicationContext(), welcome, Toast.LENGTH_LONG).show();

    }

    private void showLoginFailed(@StringRes Integer errorString) {
        Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_SHORT).show();
    }

}